package com.itheima.ydd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ydd.dto.SysMenuDto;
import com.itheima.ydd.entity.SysMenu;
import com.itheima.ydd.mapper.SysMenuMapper;
import com.itheima.ydd.service.ISysMenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    //所有菜单
    @Override
    public List<SysMenuDto> allData() {

        LambdaQueryWrapper<SysMenu> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysMenu::getPid, 0).eq(SysMenu::getType, 1);
        List<SysMenu> sysMenuList = this.list(lqw);
        List<SysMenuDto> sysMenuDtoList = new ArrayList<>(sysMenuList.size());

        for (SysMenu sysMenu : sysMenuList) {
            //先获取最高级的菜单-系统设置
            SysMenuDto sysMenuDto = new SysMenuDto();
            BeanUtils.copyProperties(sysMenu, sysMenuDto);

            LambdaQueryWrapper<SysMenu> lqw1 = new LambdaQueryWrapper<>();
            lqw1.eq(SysMenu::getPid, sysMenu.getId()).orderByAsc(SysMenu::getSort);
            List<SysMenu> sysMenuList1 = this.list(lqw1);
            List<SysMenuDto> sysMenuDtoList1 = new ArrayList<>();

            for (SysMenu menu : sysMenuList1) {
                //第二层-菜单管理
                SysMenuDto sysMenuDto1 = new SysMenuDto();
                BeanUtils.copyProperties(menu, sysMenuDto1);

                LambdaQueryWrapper<SysMenu> lqw2 = new LambdaQueryWrapper<>();
                lqw2.eq(SysMenu::getPid, menu.getId());
                List<SysMenu> list = this.list(lqw2);
                List<SysMenuDto> sysMenuDtoList2 = new ArrayList<>();
                for (SysMenu sysMenu1 : list) {
                    SysMenuDto sysMenuDto2 = new SysMenuDto();
                    BeanUtils.copyProperties(sysMenu1, sysMenuDto2);
                    sysMenuDtoList2.add(sysMenuDto2);
                }
                sysMenuDto1.setChildren(sysMenuDtoList2);
                sysMenuDtoList1.add(sysMenuDto1);
            }
            sysMenuDto.setChildren(sysMenuDtoList1);
            sysMenuDtoList.add(sysMenuDto);
        }

        return sysMenuDtoList;
    }

    @Override
    public boolean deleteById(int sysMenuId) {
        //先找,再判断下面是否有子,有就不能删
        LambdaQueryWrapper<SysMenu> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysMenu::getPid, sysMenuId);
        List<SysMenu> list = this.list(lqw);
        boolean flag = false;

        if (list.size() == 0) {
            this.removeById(sysMenuId);
            flag = true;
        }

        return flag;
    }
}
